package com.dongxing.concyrrency.chapter11;

import java.util.concurrent.TimeUnit;

/**
 * @author XavierDong
 **/
public class ExitCapture {

    public static void main(String[] args) {


        // 关闭的hook，但是kill -9的话，不会触发
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("The application will be exit.");
            notifyAndRelease();
        }));

        int i = 0;

        while (true) {
            try {
                Thread.sleep(1_000);

                System.out.println("I am working....");

                i++;
                if (i > 20) throw new RuntimeException("ERRor");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private static void notifyAndRelease() {
        System.out.println("notify to the admin");

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("will release resources(socket/file/connection)");

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("release done.");


    }
}
